﻿using AutoMapper;
using MediatR;
using RBAC_Uthorization.API.Application.Command.MenuCommand;
using RBAC_Uthorization.API.DTO;
using RBAC_Uthorization.API.DTO.Request.Menu;
using RBAC_Uthorization.API.Extensions;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Domain.Entity;
using RBAC_Uthorization.Infrstructre.Interface;
using StackExchange.Redis;
using System;

namespace RBAC_Uthorization.API.Application.CommandHandlers.MenuHandler
{
    public class MenuCreateCommandHandlers : IRequestHandler<MenuCreateCommand, ApiResult<int>>
    {
        private  readonly IMenuRepository _menuRepository;
        private  readonly IFunctionRepository _functionRepository;
        private readonly ILogger<MenuCreateCommandHandlers> _logger;
        private readonly IMapper _mapper;
        private readonly IConfiguration _configuration;
        private readonly RedisConnectionService _redisConnectionService;
        private readonly IUserInfoRepository _userInfoRepository;

        public MenuCreateCommandHandlers(IMenuRepository menuRepository, ILogger<MenuCreateCommandHandlers> logger, IMapper mapper, IFunctionRepository functionRepository, IConfiguration configuration, RedisConnectionService redisConnectionService, IUserInfoRepository userInfoRepository)
        {
            _menuRepository = menuRepository;
            _logger = logger;
            _mapper = mapper;
            _functionRepository = functionRepository;
            _configuration = configuration;
            _redisConnectionService = redisConnectionService;
            _userInfoRepository = userInfoRepository;
        }

        public async Task<ApiResult<int>> Handle(MenuCreateCommand request, CancellationToken cancellationToken)
        {
           await _functionRepository.BeginTransactionAsync();
            try
            {
                if(_configuration["Redis:Redisif"] == "1")
                {
                    
                    await _redisConnectionService.DeleteAsync($"MenuTree_{request.sys_id}");
                    await _redisConnectionService.DeleteAsync($"Menu_{request.sys_id}");
                    var userid = await _userInfoRepository.GetAllAsunc(u => u.sys_id == request.sys_id && u.del_flag == 0);
                    await _redisConnectionService.DeleteAsync($"user:{userid}:{request.sys_id}:menuIds");
                }
               
                var existingMenus = await _menuRepository.GetAllAsunc(m => m.menu_name == request.dto.menu_name&&m.sys_id==request.sys_id&&m.del_flag==0);
                if (existingMenus.Any())
                {
                    return new ApiResult<int>(ResultCode.Error, "菜单名已存在");
                }
                var map = _mapper.Map<sys_menu>(request.dto);
                map.create_by= request.CreateName;
                map.create_date=DateTime.UtcNow;
                map.sys_id = request.sys_id;
                var result = await _menuRepository.AddAsync(map);
                if (request.dto.Button.Count()>0)
                {
                    foreach (var item in request.dto.Button)
                    {
                        var fun = _mapper.Map<sys_function>(item);
                        fun.menu_id= map.id;
                        fun.create_by = request.CreateName;
                        fun.sys_id = request.sys_id;
                        fun.perms= item.is_perms;
                        fun.permission_name = item.permission_name;
                        var results = await _functionRepository.AddAsync(fun);
                    }
                  
                }

                _logger.LogInformation($"创建人{request.CreateName},权限{request.dto}成功，系统：{request.sys_id} ");
                await _functionRepository.CommitTransactionAsync();
                return new ApiResult<int>() { Data = result };
            }
            catch (Exception ex)
            {
                await _functionRepository.RollbackTransactionAsync();
                 _logger.LogError(ex, "创建菜单时发生错误");
                return new ApiResult<int>(ResultCode.Fail, "创建菜单失败");
            }
        }
    }
}
